# coding: utf-8
'''
Description: 
version: 1.0.0
Author: peng2.zhang
Date: 2021-12-02 19:57:19
LastEditors: peng2.zhang
LastEditTime: 2021-12-03 10:44:13
'''
import warnings

warnings.filterwarnings('ignore')
import requests
from datetime import datetime

from requests.auth import HTTPBasicAuth
from ci_conclude.models.db import DBConnection
from ci_conclude.services.svc_api_sonar_statistics import SonarStatisticService

def fetchValues(project):
    token = "f59b23e18b3a6874860e8ca333176a3d3d884395"
    url = f"https://sonar.ecarxgroup.com/api/issues/search?s=FILE_LINE&languages=java&projects={project}&resolved=false&rules=java%3AS1135&ps=100&facets=owaspTop10,sansTop25,severities,sonarsourceSecurity,types,tags,projects,languages,rules&additionalFields=_all&timeZone=Asia/Shanghai"
    res = requests.post(url, verify=False, auth=HTTPBasicAuth(token, ''))
    result = res.json()
    try:
        rules = {item["key"]: item["name"] for item in result["rules"]}
        rule_values = [x for x in result["facets"] if x['property'] == 'rules'][0]["values"]
        # with open(f"projects/{project}.csv", "w") as fi:
        sorted_rule_values = sorted(rule_values, key=lambda d: d['val'])
        # if project == "admapci_ad-imp-tasksplit-interface-app-meta":
        #     from code import interact
        #     interact(local=locals())
        with DBConnection() as db_conn:
            svc = SonarStatisticService(db_conn)
            for value in sorted_rule_values:
                date = datetime.now().strftime("%Y-%m-%d")
                default_value = {"sindex": value['val'], "sdate": date, "sindex_desc": rules[value['val']]} 
                kwargs = {project.replace("-", "_"): value['count']}
                # SonarStatisticService.get_or_create(defaults=default_value, **kwargs)
                res = svc._get_or_create(defaults=default_value, **kwargs)
                # if project == "admapci_ad-imp-tasksplit-interface-app-meta":
                #     line = f"{value['val']},{value['count']},{rules[value['val']]}"
                # else:
                #     line = f"{value['val']},{value['count']}"
                # fi.write(line+"\n")
                #f.writeline(f"{value['val]},{value['count'],rules[value['val']]}")

        print("finished")
    except KeyError as e:
        print(f"{project} KeyError")

if __name__ == '__main__':
    #project = 'admapci_ad-imp-build-service-app-meta'
    projects = ["admapci_ad-compare-diff-app-meta",
                "admapci_ad-daa-slam-artificial-service-app-meta",
                "admapci_ad-imp-upload-web-app-meta",
                "admapci_ad-daa-detection-service-app-meta",
                "admapci_ad-editor-web-app-meta",
                "admapci_ad-slam-artificial-web-app-meta",
                "admapci_ad-daa-segment-service-app-meta",
                "admapci_ad-daa-dynamic-removal-app-meta",
                "admapci_ad-daa-multislam-optimization-app-meta",
                "admapci_ad-daa-road-section-app-meta",
                "admapci_ad-imp-check-material-app-meta",
                "admapci_ad-imp-check-addata-app-meta",
                "admapci_ad-imp-task-web-app-meta",
                "admapci_ad-ground-concate-app-meta",
                "admapci_ad-imp-upload-service-app-meta",
                "admapci_ad-img-det-app-meta",
                "admapci_ad-imp-check-platform-app-meta",
                "admapci_ad-imp-check-workflow-app-meta",
                "admapci_ad-imp-build-service-app-meta",
                "admapci_ad-pc-seg-app-meta",
                "admapci_ad-imp-public-service-app-meta",
                "admapci_ad-slam-alignment-app-meta",
                "admapci_ad-signage-app-meta",
                "admapci_daa-pcpro-service-app-meta",
                "admapci_ad-daa-basicdata-query-service-app-meta",
                "admapci_ad-daa-multi-slam-app-meta",
                "admapci_ad-daa-extract-using-service-app-meta",
                "admapci_ad-daa-single-slam-app-meta",
                "admapci_ad-daa-standardization-app-meta",
                "admapci_ad-imp-autolink-app-meta",
                "admapci_ad-imp-edit-services-app-meta",
                "admapci_ad-img-seg-services-app-meta",
                "admapci_ad-imp-mbuild-server-app-meta",
                "admapci_ad-imp-mergeinto-service-app-meta",
                "admapci_ad-imp-matchdiff-app-meta",
                "admapci_ad-imp-postprocess-service-app-meta",
                "admapci_daa-upground-service-app-meta",
                "admapci_daa-ground-service-app-meta",
                "admapci_ad-pc-det-app-meta",
                "admapci_ad-imp-tasksplit-interface-app-meta",
                "admapci_ad-imp-process-store-app-meta",
                "admapci_ad-imp-problemdb-app-meta",
                "admapci_ad-imp-querydb-new-app-meta",
                "admapci_ad-imp-prepare-interface-manbuild-app-meta",
                "admapci_ad-imp-prepare-interface-recognition-app-meta",
                "admapci_ad-imp-daa-extract-service-app-meta",
                "admapci_ad-imp-task-service-app-meta",
                "admapci_daa-automultiple-service-app-meta",
                "admapci_admapci-imp-config",
                "admapci_admapci-imp-gateway",
                "admapci_admapci-imp-message",
                "admapci_admapci-imp-register"]
    for project in projects:
        print(project)
        fetchValues(project)
